<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ title }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="activeStep === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form ref="roleForm" :model="roleForm" :rules="roleRules">
            <el-form-item label="角色名称" style="width: 100%;" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述" style="width: 100%;">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="activeStep === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <div class="tree-title"> {{ item.title }} </div>
              <el-tree
                ref="tree"
                :data="item.children"
                node-key="id"
                default-expand-all
                :expand-on-click-node="false"
                show-checkbox
                :props="{ label: 'title' }"
                check-on-click-node
                :default-checked-keys="roleForm.perms"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-show="activeStep === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in disabledTreeList" :key="item.id" class="tree-item">
                <div class="tree-title"> {{ item.title }} </div>
                <el-tree
                  ref="disabledTree"
                  :data="item.children"
                  node-key="id"
                  default-expand-all
                  :expand-on-click-node="false"
                  show-checkbox
                  :props="{ label: 'title' }"
                  check-on-click-node
                  :default-checked-keys="roleForm.perms"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="activeStep > 1" @click="prev">上一步</el-button>
        <el-button v-if="activeStep < 3" type="primary" @click="next">下一步</el-button>
        <el-button v-if="activeStep === 3" type="primary" @click="btnOK">确认</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addRoleAPI, editRoleAPI, getAllPermissionAPI, getRoleDetailAPI } from '@/api/system-role'

export default {
  data() {
    return {
      activeStep: 1,
      roleForm: {
        roleName: '',
        remark: '',
        perms: []
      },
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      treeList: [],
      disabledTreeList: []
    }
  },
  computed: {
    title() {
      return this.$route.params.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getAllPermission()
    this.$route.params.id && this.getRoleDetail()
  },
  methods: {
    // 上一步
    prev() {
      this.activeStep--
      this.roleForm.perms = []
    },
    // 下一步
    async next() {
      if (this.activeStep === 1) {
        // 表示现在是角色信息状态
        // 校验角色信息表单
        await this.$refs.roleForm.validate()
        // 校验通过才能进入下一步
        this.activeStep++
      } else if (this.activeStep === 2) {
        // 表示现在是权限信息状态
        // 要求至少选择一项采用进入下一步
        this.roleForm.roleId || this.$refs.tree.forEach(item => {
          this.roleForm.perms.push(item.getCheckedKeys())
        })
        if (!this.roleForm.perms.some(item => item.length > 0)) {
          this.$message.error('请至少选择一项')
          return
        }
        this.activeStep++
        this.$refs.disabledTree.forEach((item, index) => {
          item.setCheckedKeys(this.roleForm.perms[index])
        })
      }
    },
    // 递归函数 --- 设置所有树节点的禁用状态
    addDisabled(list) {
      list.forEach(item => {
        item.disabled = true
        if (item.children) {
          this.addDisabled(item.children)
        }
      })
      return list
    },
    // 获取所有的功能权限
    async getAllPermission() {
      const { data } = await getAllPermissionAPI()
      this.treeList = data
      this.disabledTreeList = JSON.parse(JSON.stringify(data))
      this.disabledTreeList = this.addDisabled(this.disabledTreeList)
    },
    // 确认提交
    async btnOK() {
      // console.log(this.roleForm)
      // 判断是编辑状态还是添加状态
      if (this.roleForm.roleId) {
        const { roleName, roleId, remark, perms } = this.roleForm
        await editRoleAPI({ roleName, roleId, remark, perms })
        this.$message.success('编辑成功')
      } else {
        await addRoleAPI(this.roleForm)
        this.$message.success('添加成功')
      }
      this.$refs.roleForm.resetFields()
      this.roleForm.perms = []
      this.$router.back()
    },
    // 获取当前角色详情
    async getRoleDetail() {
      const res = await getRoleDetailAPI(this.$route.params.id)
      console.log('当前角色的详情', res)
      this.roleForm = res.data
      this.$refs.tree.forEach((item, index) => {
        item.setCheckedKeys(this.roleForm.perms[index])
      })
    }
  }
}
</script>
<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    flex-wrap: wrap;

    .tree-item {
      width: 33%;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
